<template>
  <div id="app">
    <div id="app">
      <Alert v-if="alertVisible" :message="alertMessage" @close="alertVisible = false" />
    </div>
    <div class="login-container">
      <h2>Login</h2>
      <form @submit.prevent="login">
        <div class="form-group">
          <label for="username">Username:</label>
          <input type="text" id="username" v-model="username" required>
        </div>
        <div class="form-group">
          <label for="password">Password:</label>
          <input type="password" id="password" v-model="password" required>
        </div>
        <button type="submit" class="login-btn">Login</button>
        <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
      </form>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import Alert from "@/components/Alert.vue";

export default {
  name: 'LoginPage',
  components:{
    Alert
  },
  data() {
    return {
      username: '',
      password: '',
      errorMessage: '',
      alertMessage: '',
      alertVisible: false
    }
  },
  methods: {
    async login() {
      try {
        const response = await axios.post('http://localhost:8888/userInformation/login', {
          username: this.username,
          password: this.password
        });
        console.log(response.data)
        if (response.data.data == "password right!") {
          this.alertMessage = '密码正确';
          this.alertVisible = true;
          this.$router.push('/user/user_space')
        }
        else if(response.data.data == "password wrong!"){
          this.alertMessage = '密码错误';
          this.alertVisible = true
        }
        else if(response.data.data == "user is not exit"){
          this.alertMessage = '用户不存在';
          this.alertVisible = true
        }
      } catch (error) {
        this.errorMessage = '登录失败,请稍后重试';
        console.error('Login error:', error);
      }
    }
  }
}
</script>

<style>
.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 100px;
}

.form-group {
  margin-bottom: 20px;
}

label {
  font-weight: bold;
}

input {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  width: 300px;
}

.login-btn {
  background-color: #4CAF50;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: block;
  margin: 0 auto;
}

.error-message {
  color: red;
  margin-top: 10px;
  text-align: center;
}
</style>